package com.hmdp.service.impl;

import com.hmdp.dto.Result;
import com.hmdp.entity.VoucherOrder;
import com.hmdp.mapper.VoucherOrderMapper;
import com.hmdp.service.ISeckillVoucherService;
import com.hmdp.service.IVoucherOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisIdWorker;
import com.hmdp.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.util.Collections;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Slf4j
@Service
public class VoucherOrderServiceImpl extends ServiceImpl<VoucherOrderMapper, VoucherOrder> implements IVoucherOrderService {

    @Autowired
    private ISeckillVoucherService iSeckillVoucherService;
    @Autowired
    private RedisIdWorker redisIdWorker;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private RedissonClient redissonClient;
    /**
     * 购买秒杀优惠券
     * @param voucherId
     * @return
     */

    private static final DefaultRedisScript<Long> SECKILL_SCRIPT;
    static {
        SECKILL_SCRIPT=new DefaultRedisScript<>();
        SECKILL_SCRIPT.setLocation(new ClassPathResource("seckill.lua"));
        SECKILL_SCRIPT.setResultType(Long.class);
    }
    //阻塞队列
    private BlockingQueue<VoucherOrder> orderTasks=new ArrayBlockingQueue<>(1024*1024);
    private static final ExecutorService SECKILL_ORDER_EXECUTOR = Executors.newSingleThreadExecutor();
    private class VoucherOrderHandler implements Runnable{

    @PostConstruct
    private void init(){
        SECKILL_ORDER_EXECUTOR.submit(new VoucherOrderHandler());
    }

        @Override
        public void run() {
            while (true){
                try{
                    //1.获取队列中的订单信息
                    VoucherOrder voucherOrder = orderTasks.take();
                    //2.创建订单
                    handleVoucherOrder(voucherOrder);
                }catch (Exception e){
                    log.error("处理订单异常",e);
                }
            }
        }
    }

    private void handleVoucherOrder(VoucherOrder voucherOrder) {
        //获取用户
        Long userId = voucherOrder.getUserId();
        //创建锁对象
        RLock lock = redissonClient.getLock("lock:order:" + userId);
        //获取锁
        boolean isLock = lock.tryLock();
        //判断锁是否获取成功
        if (!isLock){
           log.error("不允许重复下单");
           return;
        }
        //获取代理对象（事务）
        try {

            proxy.createVoucherOrder(voucherOrder);
        } finally {
            //释放锁
            lock.unlock();
        }
    }

    private  IVoucherOrderService proxy;
    public Result seckillVoucher(Long voucherId) {
        //获取用户
        Long userId = UserHolder.getUser().getId();
        //执行lua脚本
        Long result = stringRedisTemplate.execute(
                SECKILL_SCRIPT,
                Collections.emptyList(),
                voucherId.toString(), userId.toString()
        );
        //判断结果为0
        int r = result.intValue();
        if (r!=0){
            //不为0，代表没有购买资格
            return Result.fail(r==1? "库存不足":"不能重复下单");
        }
        //为0有资格买保存到阻塞队列
        VoucherOrder voucherOrder = new VoucherOrder();
        //订单id
        long orderId = redisIdWorker.nextId("order");
        voucherOrder.setId(orderId);
        //用户id
        voucherOrder.setUserId(userId);
        //优惠券id
        voucherOrder.setVoucherId(voucherId);
        //TODO有购买资格，保存到阻塞队列
        orderTasks.add(voucherOrder);
        //获取代理对象
         proxy = (IVoucherOrderService) AopContext.currentProxy();
        //返回订单id
        return Result.ok(orderId);



      /*  //根据优惠券id查询优惠券
        SeckillVoucher voucher = iSeckillVoucherService.getById(voucherId);
        //查看优惠券时间是否在有效期内
        if (voucher.getBeginTime().isAfter(LocalDateTime.now())){
            return Result.fail("秒杀尚未开始");
        }
        if (voucher.getEndTime().isBefore(LocalDateTime.now())){
            return Result.fail("秒杀已经结束");
        }
        //查看优惠券库存是否充足
        if (voucher.getStock()<1){
            return Result.fail("优惠券抢完了");
        }

        Long userId = UserHolder.getUser().getId();
        //创建锁对象
        //SimpleRedisLock lock = new SimpleRedisLock(stringRedisTemplate,"order:"+userId);
        RLock lock = redissonClient.getLock("lock:order:" + userId);
        //获取锁
        boolean isLock = lock.tryLock();
        //判断锁是否获取成功
        if (!isLock){
            return Result.fail("请勿重复下单");
        }
        //获取代理对象（事务）
        try {
            IVoucherOrderService proxy = (IVoucherOrderService) AopContext.currentProxy();
            return proxy.createVoucherOrder(voucherId);
        } finally {
            //释放锁
            lock.unlock();
        }*/

    }

    @Transactional
    public void createVoucherOrder(VoucherOrder voucherOrder) {
        //一人一单
            Long userId = voucherOrder.getUserId();
            //查询订单
            int count = query().eq("user_id", userId).eq("voucher_id", voucherOrder.getVoucherId()).count();
            if (count > 0) {
               log.error("用户已经购买过一次了");
               return;
            }

            //减少库存 (乐观锁解决超卖问题)
            /**
             * 错误方法总结:原来的sql语句是是修改库存的时候检查一下当前库存有没有被修改 where voucher_id=? and stock =?
             * 如果stock不等于刚开始查询的库存则报错，比如：现在有两个线程,线程1和线程2同时进行,线程1查到的库存为100,线程2也一样
             * 这时候要修改库存了，条件是当前库存数量和刚开始查到的库存数量是一致的，现在线程1刚开始查到的库存和现在的库存是一致的都是100
             * 那现在执行修改语句库存变为99了，这时候线程2想要修改库存的话就会报错，因为他刚查到的库存是100现在变成99了。
             * 这个逻辑是没问题的，但是针对于这个业务功能是有问题的，因为虽然库存变成99了但是库存还有呢又没有变成0.说明线程2是有资格购买秒杀优惠券的
             * 可由于他刚查到的库存和现在的库存不一致他就不能购买了，这显然是不合理的。
             *
             * 解决办法:只需要在运行sql语句时判断库存是否大于0
             */
            boolean success = iSeckillVoucherService.update()
                    .setSql("stock = stock-1") //set stock= stock-1
                    .eq("voucher_id", voucherOrder.getVoucherId()) //where id =? and stock >0
                    .gt("stock", 0)
                    .update();
            if (!success) {
                log.error("库存不足");
                return;
            }

            //存入数据库
            save(voucherOrder);

    }
}
